package com.lanzhou.yuanfen.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lanzhou.yuanfen.response.ServerResponsePage;
import com.lanzhou.yuanfen.response.ServerResponseResult;
import com.lanzhou.yuanfen.sys.entity.*;
import com.lanzhou.yuanfen.sys.service.*;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ClassName: {@link SysManageController}
 * @Description: SysManageController
 * @author: Lanzhou
 * @date: 2020/6/21 17:44
 * @QQ: 1627518680
 * @Copyright:2020 All rights reserved.
 */
@RestController
@RequestMapping("/sys/manage/")
public class SysManageController {

    @Resource
    private IUserService userService;
    @Resource
    private IUserRoleService userRoleService;
    @Resource
    private IRoleService roleService;
    @Resource
    private IRolePermissionService rolePermissionService;
    @Resource
    private IPermissionService permissionService;

    /**
     * 获取用户
     *
     * @param pageSize
     * @param pageIndex
     * @return
     */
    @PostMapping("pageGetUser")
    public ServerResponsePage pageGetUser(@RequestParam("pageSize") Integer pageSize,
                                          @RequestParam("pageIndex") Integer pageIndex) {
        ServerResponsePage<User> responsePage = new ServerResponsePage<>();
        IPage<User> iPage = new Page<>(pageIndex, pageSize);
        IPage<User> page = userService.page(iPage, new QueryWrapper<User>()
                .orderByAsc("username"));
        setUserRole(page);
        responsePage.setIPage(page);
        return responsePage;
    }

    /**
     * 添加或新增用户
     *
     * @param user
     * @return
     */
    @PostMapping("addOrUpdateUser")
    public ServerResponseResult addOrUpdateUser(User user) {
        userService.insertOrModify(user);
        return ServerResponseResult.success();
    }

    /**
     * 删除用户(同时删除关联)
     *
     * @param userKey
     * @return
     */
    @PostMapping("deleteUser")
    public ServerResponseResult deleteUser(@RequestParam("userKey") String userKey) {
        userService.removeUser(userKey);
        return ServerResponseResult.success();
    }




    /**
     * 获取角色
     *
     * @param pageSize
     * @param pageIndex
     * @return
     */
    @PostMapping("pageGetRole")
    public ServerResponsePage pageGetRole(@RequestParam("pageSize") Integer pageSize,
                                          @RequestParam("pageIndex") Integer pageIndex) {
        ServerResponsePage<Role> responsePage = new ServerResponsePage<>();
        IPage<Role> iPage = new Page<>(pageIndex, pageSize);
        IPage<Role> page = roleService.page(iPage, new QueryWrapper<Role>()
                .orderByAsc("name", "code"));
        setRolePerm(page);
        responsePage.setIPage(page);
        return responsePage;
    }

    /**
     * 删除角色(同时删除关联)
     *
     * @param roleKey
     * @return
     */
    @PostMapping("deleteRole")
    public ServerResponseResult deleteRole(@RequestParam("roleKey") String roleKey) {
        roleService.removeRole(roleKey);
        return ServerResponseResult.success();
    }


    /**
     * 添加或新增角色
     *
     * @param user
     * @return
     */
    @PostMapping("addOrUpdateRole")
    public ServerResponseResult addOrUpdateRole(Role user) {
        roleService.insertOrModify(user);
        return ServerResponseResult.success();
    }

    /**
     * 获取角色All
     *
     * @return
     */
    @PostMapping("getAllRole")
    public ServerResponseResult getAllRole() {
        List<Role> roles = roleService.list(new QueryWrapper<Role>()
                .orderByAsc("name", "code"));
        return ServerResponseResult.success(roles);
    }


    /**
     * 获取权限
     *
     * @param pageSize
     * @param pageIndex
     * @return
     */
    @PostMapping("pageGetPerm")
    public ServerResponsePage pageGetPerm(@RequestParam("pageSize") Integer pageSize,
                                          @RequestParam("pageIndex") Integer pageIndex) {
        ServerResponsePage<Permission> responsePage = new ServerResponsePage<>();
        IPage<Permission> iPage = new Page<>(pageIndex, pageSize);
        IPage<Permission> page = permissionService.page(iPage, new QueryWrapper<Permission>()
                .orderByAsc("name", "code"));
        responsePage.setIPage(page);
        return responsePage;
    }

    /**
     * 删除权限(同时删除关联)
     *
     * @param permKey
     * @return
     */
    @PostMapping("deletePerm")
    public ServerResponseResult deletePerm(@RequestParam("permKey") String permKey) {
        permissionService.removePerm(permKey);
        return ServerResponseResult.success();
    }

    /**
     * 添加或新增权限
     *
     * @param user
     * @return
     */
    @PostMapping("addOrUpdatePerm")
    public ServerResponseResult addOrUpdatePerm(Permission user) {
        permissionService.saveOrUpdate(user);
        return ServerResponseResult.success();
    }

    /**
     * 获取角色All
     *
     * @return
     */
    @PostMapping("getAllPerm")
    public ServerResponseResult getAllPerm() {
        List<Permission> roles = permissionService.list(new QueryWrapper<Permission>()
                .orderByAsc("name", "code"));
        return ServerResponseResult.success(roles);
    }


    /**
     * 设置用户角色
     *
     * @param page
     */
    private void setUserRole(IPage<User> page) {
        List<UserRole> userRoles = userRoleService.list();
        Map<Long, List<UserRole>> userRoleMap = userRoles.stream().collect(Collectors.groupingBy(UserRole::getUserKey));
        List<User> records = page.getRecords();
        for (User record : records) {
            Long userKey = record.getUserKey();
            List<UserRole> userRole = userRoleMap.get(userKey);
            if (userRole != null) {
                record.setUserRole(userRole);
            }
        }
    }


    /**
     * 设置角色权限
     *
     * @param page
     */
    private void setRolePerm(IPage<Role> page) {
        List<RolePermission> rolePermissions = rolePermissionService.list();
        Map<Long, List<RolePermission>> rolePermissionMap = rolePermissions.stream().collect(Collectors.groupingBy(RolePermission::getRoleKey));
        List<Role> records = page.getRecords();
        for (Role record : records) {
            Long userKey = record.getRoleKey();
            List<RolePermission> rolePermission = rolePermissionMap.get(userKey);
            if (rolePermission != null) {
                record.setRolePerm(rolePermission);
            }
        }
    }


}
